import _ from 'underscore';
const difference = _.difference
import * as XLSX from 'xlsx'
const _SheetJSFT = [
    "xlsx",
    "xlsb",
    "xlsm",
    "xls",
    "xml",
    "csv",
    "txt",
    "ods",
    "fods",
    "uos",
    "sylk",
    "dif",
    "dbf",
    "prn",
    "qpw",
    "123",
    "wb*",
    "wq*",
    "html",
    "htm"
]

export const Sheetjsftstring = _SheetJSFT.map(function (x) {
    return "." + x;
}).join(",");


export function getExceltodownload(data: unknown[][], name: string) {
    const ws = XLSX.utils.aoa_to_sheet(data)
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, name);
    // @ts-ignore
    XLSX.write(wb, { type: "file", bookType: "xlsx", file: `${name}.xlsx` });
}



export function getfiletodata(file: File, arr: string[]) {
    return new Promise((res, rej) => {
        const reader = new FileReader();
        reader.onload = e => {
            /* Parse data */
            if (!e.target) return
            const bstr = e.target.result;

            const wb = XLSX.read(bstr, {
                type: "binary"
            });
            /* Get first worksheet */
            const wsname = wb.SheetNames[0];
            const ws = wb.Sheets[wsname];
            /* Convert array of arrays */
            const data = XLSX.utils.sheet_to_json(ws, {
                header: 1
            });
            /* Update state */
            const mess = inspects(data, arr);
            if (mess) {
                if (ws["!ref"]) {
                    const data = make_cols(ws["!ref"]);
                    rej(data)
                }
            } else {
                rej('文件字段缺失')
            }
        };
        reader.readAsBinaryString(file);
    })

}

const make_cols = (refstr: string) =>
    Array(XLSX.utils.decode_range(refstr).e.c + 1)
        .fill(0)
        .map((x, i) => ({
            name: XLSX.utils.encode_col(i),
            key: i
        }));

// 检查文件内容字段是否缺失
function inspects(row: unknown[], arr: string[]) {
    const nuarr = difference(arr, row);
    if (nuarr.length !== 0) {
        return false
    }
    return false;
}

